package cn.rengy.web.framework.wxmp.upload;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.rengy.tpa.wxmp.material.TempMediaApi;
import cn.rengy.tpa.wxmp.token.AccessToken;

import cn.rengy.web.framework.sys.pub.upload.SysPubFileInfo;
import cn.rengy.web.framework.sys.pub.upload.entity.UploadResult;
import cn.rengy.web.framework.sys.pub.upload.service.PubFileService;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;

@Service
public class WxUploadService {
	
	@Autowired
	private PubFileService pubFileService;
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;

	@Value("${wxmpAppid:null}")
	private String wxmpAppid;

	/**
	 * 微信临时素材
	 * @param paramMap
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public UploadResult wxTempMedia(Map<String,Object> paramMap) throws ClientProtocolException, IOException {
		String media_id=(String)paramMap.get("media_id");
		Long file_id=MapUtils.getLong(paramMap, "file_id");
		SysPubFileInfo pubFile= pubFileService.getPubFile(file_id);
		File savePath = pubFileService.getSaveDir(pubFile);
		String appid = wxmpAppid;
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		File imgFile=TempMediaApi.get(accessToken, media_id,savePath);
		UploadResult result= pubFileService.uploaded(pubFile,paramMap, imgFile);
		return result;
	}
}
